package gov.nist.ssd.swqb.gui.components;

import gov.nist.ssd.swqb.core.search.Search;
import com.hp.hpl.jena.rdf.model.RDFNode;
import gov.nist.ssd.swqb.events.SearchNewResultEvent;
import gov.nist.ssd.swqb.listeners.SearchNewResultListener;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.Iterator;
import java.util.List;

import static gov.nist.ssd.swqb.core.Display.*;

/**
 *
 * @author Benjamin Herbomez <benjamin.herbomez@esial.com>
 */
public class SearchRunnable implements Runnable {

    private boolean run = false;
    private final Search search;
    private List<EventListener> listeners = new ArrayList<EventListener>();

    public SearchRunnable(Search s) {
        this.search = s;
    }

    @Override
    public void run() {
        Iterator<RDFNode> s = search.iterator();
        run = true;
        while (s.hasNext() && run) {
            RDFNode n = s.next();
            SearchNewResultEvent evt = new SearchNewResultEvent(this, getUri(n), n, this);
            for (EventListener l : listeners) {
                if (l instanceof SearchNewResultListener) {
                    ((SearchNewResultListener) l).newResult(evt);
                }
            }
            //TODO : find an other solution
            try {
                Thread.sleep(25);
            } catch (InterruptedException e) {
            }
        }
    }

    public void stop() {
        run = false;
        //TODO : stop the searchQuery
    }

    public boolean isRunning() {
        return run;
    }

    public void addSearchNewResultListener(SearchNewResultListener l) {
        this.listeners.add(l);
    }

    public void removeSearchNewResultListener(SearchNewResultListener l) {
        this.listeners.remove(l);
    }
}
